package co.yeye.test;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.support.v4.widget.DrawerLayout;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVOSCloud;
import com.avos.avoscloud.AVUser;
import com.avos.avoscloud.LogInCallback;
import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiscCache;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.utils.StorageUtils;

import java.io.File;

import commit.WriteDiscovery;
import fragments.AboutFragment;
import fragments.DiscoveryFragment;
import models.UserObject;


public class MainActivity extends ActionBarActivity
        implements NavigationDrawerFragment.NavigationDrawerCallbacks {

    /**
     * Fragment managing the behaviors, interactions and presentation of the navigation drawer.
     */
    private NavigationDrawerFragment mNavigationDrawerFragment;

    /**
     * Used to store the last screen title. For use in {@link #restoreActionBar()}.
     */
    private CharSequence mTitle;
    private int mNum=0;                 // 页面编号
    private boolean[] refreshList = new boolean[]{false,false,false,false,false,false,false};   // 当前被刷新的页面

    static MainActivity instance;
    String id,key;
    MyReceiver networkReceiver;				                    // 网络环境监听器
    public int networkState=Constance.NETWORK_INVALID;
    String userName="-1",userCode="-1",uri="-1",name="-1";      // 用户信息

    ImageLoader imageLoader;
    DisplayImageOptions options_cache;
    HandleOptions handleOptions;

    DiscoveryFragment discoveryFragment = DiscoveryFragment.newInstance();
    PullActivityFragment pullActivityFragment = PullActivityFragment.newInstance();
    PlaceholderFragment placeholderFragment = PlaceholderFragment.newInstance(1);
    AboutFragment aboutFragment = AboutFragment.newInstance();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        instance=this;

        // 登录leancloud
        id = "0w2jdjx6jfid5f4z68dcdz5723lk0khhi7inrg7bxid1acby";
        key = "t6o7wlr92hnymyolwdnnxnf7qtos9rmyan1qb3mxzad8fdtw";
        setAVCloudInit();

        // 注册网络环境改变监听器
        networkReceiver = new MyReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(android.net.ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(networkReceiver, filter);

        // 判断网络环境
        ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo mobileInfo = manager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
        NetworkInfo wifiInfo = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        NetworkInfo activeInfo = manager.getActiveNetworkInfo();
        if(activeInfo == null) {
            networkState=Constance.NETWORK_INVALID;
        }
        else{
            if(wifiInfo.getState() == NetworkInfo.State.CONNECTED){
                networkState=Constance.NETWORK_VALID_WIFI;
            }
            else if(mobileInfo.getState() != NetworkInfo.State.UNKNOWN){
                networkState=Constance.NETWORK_VALID_GPRS;
            }
        }

        ActionBar actionBar = this.getSupportActionBar();
        actionBar.setTitle("发布活动信息");
        actionBar.setBackgroundDrawable(getResources().getDrawable(R.color.blue));

        refreshList[getLastPageNum()]=true;     // 这个页面暂时不要刷新，避免重复刷新
        mNavigationDrawerFragment = (NavigationDrawerFragment)
                getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
        mTitle = getTitle();

        // Set up the drawer.
        mNavigationDrawerFragment.setUp(
                R.id.navigation_drawer,
                (DrawerLayout) findViewById(R.id.drawer_layout));

        FragmentTransaction transaction = getSupportFragmentManager()
                .beginTransaction();
        transaction
                .add(R.id.container,discoveryFragment)
                .add(R.id.container,pullActivityFragment)
                .add(R.id.container,placeholderFragment)
                .add(R.id.container,aboutFragment)
                .commit();

        startInit();
        imageLoaderInit_cache();

        handleOptions = new HandleOptions(this);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 从register页面返回
        if(requestCode==100){
            if(resultCode==RESULT_OK){
                String path = data.getStringExtra("path");
                if(!path.equals("-1"))
                    mNavigationDrawerFragment.setUserImg(data.getStringExtra("path"),
                            data.getStringExtra("name"));
                this.userName=data.getStringExtra("name");
                this.uri=data.getStringExtra("path");
                this.userCode=data.getStringExtra("code");
            }
        }
    }

    @Override
    public void onNavigationDrawerItemSelected(int position) {
        // update the main content by replacing fragments
        switchContent(position);
    }

    /**
     * 跳转页面
     * @param pageNum 跳转到的页面编号
     */
    public void switchContent(int pageNum) {
        FragmentTransaction transaction = getSupportFragmentManager()
                .beginTransaction();
        // 全部隐藏
        transaction
                .hide(discoveryFragment)
                .hide(pullActivityFragment)
                .hide(placeholderFragment)
                .hide(aboutFragment);
        // 显示
        switch(pageNum){
            case 0 : transaction.show(pullActivityFragment);break;
            case 1 : transaction.show(discoveryFragment);break;
            case 2 : transaction.show(placeholderFragment);break;
            case 6 : transaction.show(aboutFragment);break;
            default: transaction.show(pullActivityFragment);
        }
        // 刷新，前提是网络可用
        if(networkState!=Constance.NETWORK_INVALID && refreshList[pageNum]==false) {
            switch (pageNum) {
                case 1 : discoveryFragment.networkChanged(networkState);break;
                case 6 : aboutFragment.networkChanged(networkState);break;
                default : break;
            }
            refreshList[pageNum]=true;
        }
        // 切换动画
        transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
        transaction.commit();

        onSectionAttached(pageNum);
    }

    public void onSectionAttached(int number) {
        //Log.v("YeYe","number="+String.valueOf(number));
        mNum=number;
        switch (mNum) {
            case 0:
                mTitle = getString(R.string.item_1);
                break;
            case 1:
                mTitle = getString(R.string.item_2);
                break;
            case 2:
                mTitle = getString(R.string.item_3);
                break;
            case 3:
                mTitle = getString(R.string.item_4);
                break;
            case 4:
                mTitle = getString(R.string.item_5);
                break;
            case 5:
                mTitle = getString(R.string.item_6);
                break;
            case 6:
                mTitle = getString(R.string.item_7);
                break;
        }
    }

    public void restoreActionBar() {
        ActionBar actionBar = getSupportActionBar();
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
        actionBar.setDisplayShowTitleEnabled(true);
        actionBar.setTitle(mTitle);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        if (!mNavigationDrawerFragment.isDrawerOpen()) {
            // Only show items in the action bar relevant to this screen
            // if the drawer is not showing. Otherwise, let the drawer
            // decide what to show in the action bar.
            //Log.v("YeYe", String.valueOf(mNum));
            switch(mNum){
                case 1 : getMenuInflater().inflate(R.menu.main_discovery, menu);break;
                default : getMenuInflater().inflate(R.menu.main, menu);
            }
            //getMenuInflater().inflate(R.menu.main, menu);
            restoreActionBar();
            return true;
        }
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }
        else if(handleOptions.handlerOption(id)){
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {
        /**
         * The fragment argument representing the section number for this
         * fragment.
         */
        private static final String ARG_SECTION_NUMBER = "section_number";

        /**
         * Returns a new instance of this fragment for the given section
         * number.
         */
        public static PlaceholderFragment newInstance(int sectionNumber) {
            PlaceholderFragment fragment = new PlaceholderFragment();
            Bundle args = new Bundle();
            args.putInt(ARG_SECTION_NUMBER, sectionNumber);
            fragment.setArguments(args);
            return fragment;
        }

        public PlaceholderFragment() {
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_main, container, false);
            return rootView;
        }

        @Override
        public void onAttach(Activity activity) {
            super.onAttach(activity);
            //((MainActivity) activity).onSectionAttached(
             //       getArguments().getInt(ARG_SECTION_NUMBER));
        }
    }

    public static MainActivity getInstance(){
        return instance;
    }

    /**
     * 登录初始化
     */
    private void startInit(){
        SharedPreferences sharedPreferences = getSharedPreferences("MyOpto", Context.MODE_PRIVATE);
        boolean isLogin = sharedPreferences.getBoolean("isLogin",false);
        // 自动登录
        if(isLogin){
            userName = sharedPreferences.getString("user_name","-1");
            userCode = sharedPreferences.getString("user_code","-1");
            name = sharedPreferences.getString("name","-1");
            // 验证图片是否存在
            uri = sharedPreferences.getString(userCode+"_img_uri","-1");
            if(uri.equals("-1")){
                Toast.makeText(getBaseContext(),"用户信息错误，请重新登录",Toast.LENGTH_SHORT).show();
                return;
            }
            AVUser avUser = new AVUser();
            avUser.logInInBackground(userName,sharedPreferences.getString("pwk","-1"),new LogInCallback<AVUser>() {
                @Override
                public void done(AVUser avUser, AVException e) {
                    if(e!=null)
                        Toast.makeText(getBaseContext(),"登录错误",Toast.LENGTH_SHORT).show();
                }
            });
        }
        mNavigationDrawerFragment.setUserImg(uri,userName);
        // 初始化配置标题栏
        int pageNum = getLastPageNum();
        onNavigationDrawerItemSelected(pageNum);
        mNavigationDrawerFragment.selectItem(pageNum);
        //onSectionAttached(0);
        //restoreActionBar();
    }

    /**
     * 获取保存的页面编号
     */
    private int getLastPageNum(){
        SharedPreferences sharedPreferences = getSharedPreferences("MyOpto", Context.MODE_PRIVATE);
        return sharedPreferences.getInt("pageNum",0);
    }

    @Override
    public void onBackPressed() {
        moveTaskToBack(true);
        //super.onBackPressed();
    }

    @Override
    protected void onPause() {
        //Log.v("YeYe","onPause");
        // 保存页面编号
        SharedPreferences sharedPreferences = getSharedPreferences("MyOpto",MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putInt("pageNum",mNum);
        editor.commit();
        super.onPause();
    }

    private void setAVCloudInit(){
        AVOSCloud.initialize(getBaseContext(),id,key);
        //isNetConnected=true;
    }

    /**
     * 配置侧边栏信息
     */
    public void setSlideInfo(String uri,String userName,String code,String name){
        if(userName!=null)
            this.userName=userName;
        if(uri!=null)
            this.uri=uri;
        if(code!=null)
            this.userCode=code;
        if(name!=null)
            this.name=name;
        if(uri!=null && userName!=null)
            mNavigationDrawerFragment.setUserImg(uri,userName);
        // 刷新Discovery的图像适配器内的用户信息
        discoveryFragment.refreshAdapter();
    }

    /**
     * 获取网络连接状态
     * @return 网络是否已连接
     */
    public int getNetState(){
        return networkState;
    }

    /**
     * 获取登陆的用户信息
     */
    public UserObject getUser(){
        UserObject userObject = new UserObject();
        userObject.setUser_name(this.userName);
        userObject.setUri(this.uri);
        userObject.setUser_code(this.userCode);
        userObject.setName(name);
        return userObject;
    }

    /**
     * 注销
     */
    public void logOut(){
        this.userCode="-1";
        this.userName="-1";
        this.name="-1";
        this.uri="-1";
        // 保存文件路径
        SharedPreferences sharedPreferences = getSharedPreferences("MyOpto", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor;
        editor = sharedPreferences.edit();
        //String user_code = code.getText().toString();
        editor.putBoolean("isLogin",false);
        editor.commit();
        mNavigationDrawerFragment.setUserImg(uri,userName);
        // 刷新Discovery的图像适配器内的用户信息
        //Toast.makeText(getBaseContext(),"Logout",Toast.LENGTH_SHORT).show();
        discoveryFragment.refreshAdapter();
    }

    // 网络环境变化监听器
    public class MyReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            // TODO Auto-generated method stub
            //Toast.makeText(context, intent.getAction(), 1).show();
            ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mobileInfo = manager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
            NetworkInfo wifiInfo = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
            NetworkInfo activeInfo = manager.getActiveNetworkInfo();
            if(activeInfo == null) {
                Toast.makeText(context, "网络断开", Toast.LENGTH_SHORT).show();
                networkState=Constance.NETWORK_INVALID;
            }
            else{
                if(wifiInfo.getState() == NetworkInfo.State.CONNECTED){
                    //Toast.makeText(context, "WiFi network connected", Toast.LENGTH_SHORT).show();
                    setAVCloudInit();
                    networkState=Constance.NETWORK_VALID_WIFI;
                }
                else if(mobileInfo.getState() != NetworkInfo.State.UNKNOWN){
                    setAVCloudInit();
                    //Toast.makeText(context, "GRPS network connected", Toast.LENGTH_SHORT).show();
                    networkState=Constance.NETWORK_VALID_GPRS;
                }
            }
            broadcastNetworkStateChanged();
        }

    }

    // 通知各fragment网络状态改变
    private void broadcastNetworkStateChanged(){
        switch(mNum){
            case 1 : discoveryFragment.networkChanged(networkState);break;
            case 6 : aboutFragment.networkChanged(networkState);break;
            default : break;
        }
        // 配置刷新列表
        refreshList[mNum]=true;
    }

    public ImageLoader getImageLoader(){
        return imageLoader;
    }

    public DisplayImageOptions getOptionCache(){
        return options_cache;
    }

    private void imageLoaderInit_cache(){
        File cacheDir = StorageUtils.getOwnCacheDirectory(getBaseContext(), "imageloader/Cache");
        ImageLoaderConfiguration config = new ImageLoaderConfiguration
                .Builder(getBaseContext())
                .threadPriority(Thread.NORM_PRIORITY - 2)
                .denyCacheImageMultipleSizesInMemory()
                .discCacheFileNameGenerator(new Md5FileNameGenerator())
                .tasksProcessingOrder(QueueProcessingType.LIFO)
                .discCache(new UnlimitedDiscCache(cacheDir))//自定义缓存路径
                .build();//开始构建
        imageLoader = ImageLoader.getInstance();
        imageLoader.init(config);//全局初始化此配置

        options_cache = new DisplayImageOptions.Builder()
                .showImageOnLoading(R.drawable.ic_launcher) //设置图片在下载期间显示的图片
                .showImageForEmptyUri(R.drawable.ic_launcher)//设置图片Uri为空或是错误的时候显示的图片
                .showImageOnFail(R.drawable.ic_launcher)  //设置图片加载/解码过程中错误时候显示的图片
                .cacheInMemory(true)						// 设置下载的图片是否缓存在内存中
                .cacheOnDisk(true)							// 设置下载的图片是否缓存在SD卡中
                //.resetViewBeforeLoading(true)//设置图片在下载前是否重置，复位
                //.displayer(new RoundedBitmapDisplayer(20))//是否设置为圆角，弧度为多少
                //.displayer(new FadeInBitmapDisplayer(100))//是否图片加载好后渐入的动画时间
                .build();//构建完成
    }

}
